package com.example.teamtribe.main.club.posting;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.teamtribe.R;
import com.example.teamtribe.base.BaseActivity;
import com.example.teamtribe.common.userinfo.UserInfoActivity;
import com.example.teamtribe.database.Posting;
import com.example.teamtribe.database.User;
import com.example.teamtribe.utils.Utility;
import com.example.zhouwei.library.CustomPopWindow;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class PostingActivity extends BaseActivity implements View.OnClickListener, PostingContract.View, XRecyclerView.LoadingListener, TextWatcher {

    public static final int DELETE = -100;
    public static final int MODIFY = -101;

    private CustomPopWindow customPopWindow;
    private View popView;
    private ImageView ivMore;
    private ImageView ivHead;
    private TextView tvNickname;
    private EditText etComment;

    private List<String> imageData;
    private PhotosAdapter adapter_p;
    private XRecyclerView rvComments;
    private List<Posting> commentData;
    private CommentAdapter adapter_c;
    private Button btSend;

    private Posting posting;
    private int teamId;
    private User user;
    private PostingContract.Presenter presenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_posting);
        ivMore = findViewById(R.id.iv_more);
        ivHead = findViewById(R.id.iv_head);
        tvNickname = findViewById(R.id.tv_nickname);
        etComment = findViewById(R.id.et_comment);
        etComment.addTextChangedListener(this);
        imageData = new ArrayList<>();
        adapter_p = new PhotosAdapter(imageData);
        commentData = new ArrayList<>();
        adapter_c = new CommentAdapter(commentData);
        RecyclerView rvPhotos = findViewById(R.id.rv_photos);
        rvPhotos.setLayoutManager(new GridLayoutManager(this, 3));
        rvPhotos.setAdapter(adapter_p);
        rvComments = findViewById(R.id.rv_comments);
        rvComments.setLayoutManager(new LinearLayoutManager(this));
        rvComments.setAdapter(adapter_c);
        rvComments.setNestedScrollingEnabled(false);
        rvComments.setPullRefreshEnabled(false);
        rvComments.setLoadingListener(this);
        btSend = findViewById(R.id.bt_send);
        ivHead.setOnClickListener(this);
        btSend.setOnClickListener(this);

        popView = LayoutInflater.from(this).inflate(R.layout.pop_posting, null);
        popView.findViewById(R.id.tv_modify).setOnClickListener(this);
        popView.findViewById(R.id.tv_delete).setOnClickListener(this);
        customPopWindow = new CustomPopWindow.PopupWindowBuilder(this)
                .setView(popView)
                .create();

        Intent extra = getIntent();
        posting = extra.getParcelableExtra("posting");
        teamId = extra.getIntExtra("teamId", 0);
        if (extra.getBooleanExtra("isComment", false)) {
            toComment();
        }
        if (posting.getUserId() == Utility.getUser().getRealId()) {
            //ivMore.setVisibility(View.VISIBLE);
            //ivMore.setOnClickListener(this);
        }
        presenter = new PostingPresenter(this);
        ((TextView) findViewById(R.id.tv_title)).setText("看帖");
        setInfo();
        if (posting.getRealId() > 100000) {
            setUser(Utility.getT(posting.getUserId(), User.class));
            setHead();
            setImage(posting.getImages());
            setImage();
            addComment(DataSupport.where("targetId = ?", posting.getRealId() + "").find(Posting.class));
            setCommentUser();
        } else {
            presenter.start(posting.getRealId(), posting.getImages());
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_more:
                customPopWindow.showAsDropDown(ivMore, 0, 0);
                break;
            case R.id.iv_head:
                User user = Utility.getT(posting.getUserId(), User.class);
                if (user != null) {
                    Intent intent = new Intent(this, UserInfoActivity.class);
                    intent.putExtra("user", user);
                    startActivity(intent);
                }
                break;
            case R.id.bt_send:
                presenter.comment(teamId, etComment.getText().toString(), posting.getRealId());
                break;
            case R.id.tv_modify:
                break;
            case R.id.tv_delete:
                presenter.delete(posting.getRealId());
                break;
            default:
                break;
        }
    }

    @Override
    public void setUser(final User user) {
        this.user = user;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tvNickname.setText(user.getNickname());
            }
        });
    }

    @Override
    public void setHead() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (!PostingActivity.this.isDestroyed()) {
                    Glide.with(PostingActivity.this).load(Utility.getUri(user.getPortrait())).into(ivHead);
                }
            }
        });
    }

    @Override
    public void setImage(List<String> images) {
        this.imageData.addAll(images);
    }

    @Override
    public void setImage() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                adapter_p.notifyDataSetChanged();
            }
        });
    }

    @Override
    public void addComment(Posting comment) {
        commentData.add(comment);
        Collections.sort(commentData);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                adapter_c.notifyDataSetChanged();
            }
        });
    }

    @Override
    public void addComment(List<Posting> comments) {
        commentData.addAll(comments);
        Collections.sort(commentData);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                adapter_c.notifyDataSetChanged();
            }
        });
    }

    @Override
    public void setCommentUser() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Log.d("设置评论", "设置评论");
                adapter_c.notifyDataSetChanged();
            }
        });
    }

    @Override
    public void setCommentHead() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Log.d("设置评论头像", "设置评论头像");
                adapter_c.notifyDataSetChanged();
            }
        });
    }

    @Override
    public void complete() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                rvComments.loadMoreComplete();
            }
        });
    }

    @Override
    public void clearText() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                etComment.getText().clear();
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
            }
        });
    }

    @Override
    public void next(int resultCode) {
        Intent intent = new Intent();
        intent.putExtra("posting", posting);
        setResult(resultCode, intent);
        finish();
    }

    @Override
    public void onRefresh() {

    }

    @Override
    public void onLoadMore() {
        presenter.getComments(posting.getRealId(), commentData.size());
    }

    @Override
    public void showProgress() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                btSend.setEnabled(false);
            }
        });
    }

    @Override
    public void hideProgress() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                btSend.setEnabled(true);
            }
        });
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (etComment.getText().length() > 0) {
            btSend.setBackground(getDrawable(R.drawable.button_stroke));
            btSend.setTextColor(getResources().getColor(R.color.colorAccent));
            btSend.setEnabled(true);
        } else {
            btSend.setBackground(getDrawable(R.drawable.button_stroke_unable));
            btSend.setTextColor(getResources().getColor(R.color.unable));
            btSend.setEnabled(false);
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    private void setInfo() {
        TextView tvTime = findViewById(R.id.tv_info);
        TextView tvTitle = findViewById(R.id.tv_posting_title);
        TextView tvContent = findViewById(R.id.tv_content);
        tvTime.setText(posting.getEditTime());
        tvTitle.setText(posting.getTitle());
        tvContent.setText(Html.fromHtml(posting.getContent()));
    }

    private void toComment() {
        etComment.setFocusable(true);
        etComment.setFocusableInTouchMode(true);
        etComment.requestFocus();
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(etComment, 0);
    }
}
